package me.xiaoyan.java.spring.controller;

import me.xiaoyan.java.spring.po.Link;
import me.xiaoyan.java.spring.service.LinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/link")
public class LinkController {
    private LinkService linkService;

    @Autowired
    public void setLinkService(LinkService linkService) {
        this.linkService = linkService;
    }

    @PostMapping("/save")
    public String saveLink(MultipartFile icon, MultipartFile picture, String name, String description, String url, String content, Integer categoryId,
                           HttpServletRequest request) {
        // 获取上传文件目录真实路径
        String dir = request.getSession().getServletContext().getRealPath("fileUpload");

        try {
            Link link = new Link();
            link.setIcon(saveFile(dir,icon)); // 请求路径
            link.setPicture(saveFile(dir,picture));
            link.setName(name);
            link.setUrl(url);
            link.setDescription(description);
            link.setCategoryId(categoryId);
            link.setContent(content);
            linkService.save(link);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
            return "fail";
        }


    }

    /**
     * 保存上传的文件并返回请求路径
     * @param dir
     * @param file
     * @return
     * @throws IOException
     */
    private String saveFile(String dir, MultipartFile file) throws IOException {
       // 获取保存的路径 - 绝对路径
        String savePath = dir + '/' + file.getOriginalFilename();
        file.transferTo(new File(savePath)); // 直接保存 (本质是移动)
        return "fileUpload/" + file.getOriginalFilename();
    }

    /**
     * 直接返回链接对象json数据
     * @param id
     * @return
     */
    @RequestMapping("/{id}")
    @ResponseBody
    public Link showLink(@PathVariable("id") Integer id){
        return linkService.getLinkById(id);
    }

    @PostMapping("/update")
    @ResponseBody
    public String updateLink(Link link){
        linkService.save(link);
        return "success";
    }
}
